package com.samuel.blog.interceptor;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.samuel.blog.utils.StringUtils;


/**
 * 拦截mybatis的StatementHandler 
 *   记录所有的sql
 * @author kaiji
 * @since 2018-02-26
 *
 */
@Intercepts({@Signature(type=StatementHandler.class, method="prepare", args={Connection.class, Integer.class})})
public class ShowSqlInterceptor implements Interceptor {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private Boolean close;
	
	@Override
	public Object intercept(Invocation it) throws Throwable {
		if (close) {
			StatementHandler sh = (StatementHandler)it.getTarget();
			BoundSql boundSql = sh.getBoundSql();

			/*MetaObject metaObject = SystemMetaObject.forObject(sh);
			metaObject.setValue("boundSql.sql", "select * from yun_author where author_id = '2'");*/
			String sql = boundSql.getSql();
			sql = StringUtils.formateSql(sql);
			logger.info("sql ===> 【{}】", sql);
		}
		return it.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		String flag = properties.get("close").toString();
		if (null == flag || "".equals(flag)) {
			this.close = false;
		}
		this.close = "true".equals(flag) ? true : false;
	}


}
